package com.cn.medicalcare.controller.servlet.login;

import com.cn.medicalcare.customtool.JsonTool;
import com.cn.medicalcare.pojo.Admin;
import com.cn.medicalcare.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

@WebServlet("/login.json")
public class LoginServlet extends HttpServlet {

    private LoginService loginService=LoginService.getInstance();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        PrintWriter pw=resp.getWriter();
        Map<String,Object> map=new LinkedHashMap<>();
        if((username==null || username.length()==0)||( password==null || password.length()<5)){
            //用户名或密码格式错误,返回400
            map.put("status","400");
            pw.print(JsonTool.toJson(map));
        }else {
            switch (loginService.isLogin(username,password,req)){
                case 0://用户名不存在
                    map.put("status","404");
                    map.put("message","用户名不存在");
                    pw.print(JsonTool.toJson(map));
                    break;
                case 1:
                    //用户未激活
                    map.put("status","404");
                    map.put("message","用户名未激活");
                    pw.print(JsonTool.toJson(map));
                    break;
                case 2:
                    //验证不通过返回404
                    map.put("status","404");
                    map.put("message","密码错误");
                    pw.print(JsonTool.toJson(map));
                    break;
                case 3:
                    //验证通过返回200
                    map.put("status","200");
                    map.put("sessionId",req.getAttribute("sessionId").toString());
                    map.put("admin_user",req.getAttribute("admin_user"));
                    pw.print(JsonTool.toJson(map));
                    break;
            }
        }
    }
}
